## 作者： 修炼者 7457222@qq.com 
## 日期： 2024-12-08
## 描述： 用以生成数据库表的服务类
<%!
    import public.jygt_coder_utitls as JYGTCoderUtils
    from datetime import datetime
%><%def name="generate_test(
    table_name, 
    columns,
    indexes
)">${JYGTCoderUtils.get_desc()}
import os
import sys
import random

from datetime import datetime, timedelta

start_date = datetime(2020, 1, 1)
end_date = datetime(2024, 12, 31)

def generate_random_date():
    delta = end_date - start_date
    random_days = random.randint(0, delta.days)
    random_date = start_date + timedelta(days=random_days)
    return random_date


# 添加当前文件所在目录到Python路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)

# 添加包的父目录到Python路径中
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)


import pytest

from service.${JYGTCoderUtils.get_service_class_name(table_name)} import ${JYGTCoderUtils.get_service_class_name(table_name)}
from entity.${JYGTCoderUtils.get_entity_class_name(table_name)} import ${JYGTCoderUtils.get_entity_class_name(table_name)}


@pytest.fixture
def getObj():
    return ${JYGTCoderUtils.get_service_class_name(table_name)}()

columns = ${columns}

import string

def generate_random_string(length):
    letters = string.ascii_letters  # Includes both uppercase and lowercase letters
    random_string = ''.join(random.choice(letters) for _ in range(length))
    return random_string

def generate_test_data(columns):
    res = []
    while len(res) < 10:
        test_data = {}
        for column in columns:
            col_name = column['name']
            col_type = column['type']
            if col_type == 'Integer':
                test_data[col_name] = random.randint(1, 100)
            elif col_type.startswith('String'):
                test_data[col_name] = f'test_{col_name}{generate_random_string(10)}'
            elif col_type == 'Text':
                test_data[col_name] = f'test_{col_name}{generate_random_string(10)}'
            elif col_type == 'DateTime':
                test_data[col_name] = generate_random_date()
            elif col_type == 'Boolean':
                test_data[col_name] = True
            else:
                test_data[col_name] = None
        res.append(test_data)
    return res

def generate_test_data_primary(columns):
    res = []
    while len(res) < 10:
        test_data = ''
        for column in columns:
            col_name = column['name']
            col_type = column['type']
            col_primary_key = column['primary_key']

            if col_primary_key.startswith('primary_key'):
                if col_type == 'Integer':
                    test_data = random.randint(1, 100)
                elif col_type.startswith('String'):
                    test_data = f'test_{col_name}{generate_random_string(10)}'
                elif col_type == 'Text':
                    test_data = f'test_{col_name}{generate_random_string(10)}'
                elif col_type == 'DateTime':
                    test_data = generate_random_date()
                elif col_type == 'Boolean':
                    test_data = True
                else:
                    test_data = None
        res.append(test_data)
    return res

def test_getAll(getObj):

    res = getObj.getAll()

    if res['total'] == 0:
        return
    
    print(f"total: {res['total']},pages: {res['pages']},current_page: {res['current_page']}")

    for itm in res["items"]:
        print(itm)
        assert isinstance(itm, ${JYGTCoderUtils.get_entity_class_name(table_name)})

def test_add_and_get_by(getObj):
    """
    测试 add 方法和 getBy 方法。
    """
    test_data = generate_test_data(columns)

    # 添加数据
    test_data_ed =  getObj.add(test_data)

    if len(test_data_ed) == 0:
        return

    # 获取数据
    % if JYGTCoderUtils.get_primary_from_indexes(indexes):
    primary_key = getattr(test_data_ed[0],'${JYGTCoderUtils.get_primary_from_indexes(indexes)}')
    retrieved_data = getObj.getBy${JYGTCoderUtils.snake_to_camel_big('PRIMARY')}(primary_key)
   
    assert retrieved_data is not None

    for column in columns:
        col_name = column['name']
        assert getattr(retrieved_data, col_name) == getattr(test_data_ed[0], col_name)
    
    % endif

    
def test_update_and_get_by(getObj):
    """
    测试 add 方法和 getBy 方法。
    """
    test_data = generate_test_data(columns)

    # 添加数据
    test_data_ed =  getObj.update(test_data)

    if len(test_data_ed) == 0:
        return

    # 获取数据
    % if JYGTCoderUtils.get_primary_from_indexes(indexes):
    primary_key = getattr(test_data_ed[0],'${JYGTCoderUtils.get_primary_from_indexes(indexes)}')
    retrieved_data = getObj.getBy${JYGTCoderUtils.snake_to_camel_big('PRIMARY')}(primary_key)
   
    assert retrieved_data is not None

    for column in columns:
        col_name = column['name']
        assert getattr(retrieved_data, col_name) == getattr(test_data_ed[0], col_name)
    
    % endif

    


def test_replace_and_get_by(getObj):
    """
    测试 add 方法和 getBy 方法。
    """
    test_data = generate_test_data(columns)

    # 添加数据
    test_data_ed =  getObj.replace(test_data)

    assert len(test_data_ed) == len(test_data)

    # 获取数据
    % if JYGTCoderUtils.get_primary_from_indexes(indexes):
    primary_key = getattr(test_data_ed[0],'${JYGTCoderUtils.get_primary_from_indexes(indexes)}')
    retrieved_data = getObj.getBy${JYGTCoderUtils.snake_to_camel_big('PRIMARY')}(primary_key)
   
    assert retrieved_data is not None
    
    for column in columns:
        col_name = column['name']
        assert getattr(retrieved_data, col_name) == getattr(test_data_ed[0], col_name)
    
    % endif


def test_delete(getObj):
    """
    测试 delete 方法。
    """
    test_data = generate_test_data_primary(columns)

    # 添加数据
    test_data_ed = getObj.delete(test_data)

    for itm in test_data_ed:
        primary_key = getattr(test_data_ed[0],'${JYGTCoderUtils.get_primary_from_indexes(indexes)}')
        # 获取删除后的数据
        % if JYGTCoderUtils.get_primary_from_indexes(indexes):
        retrieved_data = getObj.getBy${JYGTCoderUtils.snake_to_camel_big('PRIMARY')}(primary_key)
        assert retrieved_data is None
        % endif

    

</%def>${generate_test(table_name, columns, indexes)}        